package com.stars.empoly.activity

import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import com.qmuiteam.qmui.kotlin.onClick
import com.stars.empoly.R
import com.stars.empoly.base.MBActivity
import com.stars.empoly.databinding.ActivityMainBinding
import com.stars.empoly.fragment.*
import com.stars.empoly.inte.ChoiceLocation
import com.stars.empoly.vmodel.MainVModel
import com.tencent.mmkv.MMKV
import com.trailer.base.utils.KeySimulateUtils
import com.stars.empoly.update.bean.UpdateBean
import com.stars.empoly.update.showUpgradeDialog
import com.stars.empoly.utils.CurrentOneLocationUtils
import com.trailer.base.base.BApp
import com.trailer.base.base.BApp.Companion.instance
import java.util.*

/**
 *
 *on 2020/12/4
 */
class MainActivity : MBActivity<MainVModel, ActivityMainBinding>() {

    var fragments = emptyArray<Fragment>()

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        initData()

        vm.getAppConfig()

        vm.bean.observe(this){

            var code=instance()?.config()?.getVersionCode()
            if(code!!<it.version) {
                showUpgradeDialog(it)
            }
        }

//       // 测试升级
//        val data = UpdateBean(2,"1.0.1","发现新版本","1、修复了已知可能影响体验的BUG\n" +
//                "                \\n2、提升直播及在线聊天的稳定性\\n3、多种优化等你发现","https://app.huacunkj.com/profile/upload/2022/10/09/xiaomi_1.0.1.apk",0,0)  //这是我这里后台返回的Model，你可以根据自己项目进行修改
//        showUpgradeDialog(data)

        //获取用户的当前位置
        lifecycleScope.launchWhenCreated {
            CurrentOneLocationUtils.getStartLocal(context() as MainActivity, object :
                ChoiceLocation {
                override fun onRestuse(lat: String, lng: String, city: String) {
                    MMKV.defaultMMKV().putString("city", city)

                    MMKV.defaultMMKV().putString("lat", lat)
                    MMKV.defaultMMKV().putString("lng", lng)
                }
            })
        }





    }

    override fun listeners() {
        super.listeners()

        binding.llOne.onClick {
            binding.imgOne.setImageResource(R.drawable.menu_one_focus)
            binding.tvOne.setTextColor(Color.parseColor("#333333"))
            binding.imgTwo.setImageResource(R.drawable.menu_two)
            binding.tvTwo.setTextColor(Color.parseColor("#999999"))
            binding.imgThree.setImageResource(R.drawable.menu_three)
            binding.tvThree.setTextColor(Color.parseColor("#999999"))
            binding.imgFour.setImageResource(R.drawable.menu_four)
            binding.tvFour.setTextColor(Color.parseColor("#999999"))

            switchContent(0)

        }
        binding.llFour.onClick {
            binding.imgFour.setImageResource(R.drawable.menu_four_focus)
            binding.tvFour.setTextColor(Color.parseColor("#333333"))
            binding.imgOne.setImageResource(R.drawable.menu_one)
            binding.tvOne.setTextColor(Color.parseColor("#999999"))
            binding.imgTwo.setImageResource(R.drawable.menu_two)
            binding.tvTwo.setTextColor(Color.parseColor("#999999"))
            binding.imgThree.setImageResource(R.drawable.menu_three)
            binding.tvThree.setTextColor(Color.parseColor("#999999"))

            switchContent(1)
        }
        binding.llTwo.onClick {
            binding.imgOne.setImageResource(R.drawable.menu_one)
            binding.tvOne.setTextColor(Color.parseColor("#999999"))
            binding.imgTwo.setImageResource(R.drawable.men_two_focus)
            binding.tvTwo.setTextColor(Color.parseColor("#333333"))
            binding.imgThree.setImageResource(R.drawable.menu_three)
            binding.tvThree.setTextColor(Color.parseColor("#999999"))
            binding.imgFour.setImageResource(R.drawable.menu_four)
            binding.tvFour.setTextColor(Color.parseColor("#999999"))
            switchContent(2)
        }
        binding.llThree.onClick {
            binding.imgOne.setImageResource(R.drawable.menu_one)
            binding.tvOne.setTextColor(Color.parseColor("#999999"))
            binding.imgTwo.setImageResource(R.drawable.menu_two)
            binding.tvTwo.setTextColor(Color.parseColor("#999999"))
            binding.imgThree.setImageResource(R.drawable.menu_three_focus)
            binding.tvThree.setTextColor(Color.parseColor("#333333"))
            binding.imgFour.setImageResource(R.drawable.menu_four)
            binding.tvFour.setTextColor(Color.parseColor("#999999"))
            switchContent(3)
        }
    }


    private fun initData() {
        initMainMenu()

    }

    private fun initMainMenu() {
        val oneFragment = HomeClientFragment()
        val fourFragment = HomeMechFragemnt()
        val twoFragment = HomeOrderFragment()
        val threeFragment = HomeMeFragemnt()


        fragments = arrayOf(
            oneFragment,
            fourFragment,
            twoFragment,
            threeFragment

        )

        switchContent(0)

    }


    private fun switchContent(index: Int) {

        val childFragmentManager: FragmentManager = supportFragmentManager
        val transaction = childFragmentManager.beginTransaction()
        var fragment = childFragmentManager.findFragmentByTag("tab_$index")
        if (fragment == null) {//还未加载

            fragment = fragments[index]
            if (fragment != null) {
                transaction.add(R.id.container, fragment, "tab_$index")
            }
        } else {
            transaction.show(fragment)
        }
        for (i in fragments.indices) {
            fragment = childFragmentManager.findFragmentByTag("tab_$i")
            if (fragment == null || index == i) {
                continue
            }
            transaction.hide(fragment)
        }
        transaction.commitAllowingStateLoss()
    }


    override fun vmClass(): Class<MainVModel> {
        return MainVModel::class.java
    }

    override fun binding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return null
    }

    override fun transluent(): Boolean {
        return true
    }

    /**
     * 双击退出函数
     */
    private var isExit = false

    /**
     * 菜单、返回键响应
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click() //调用双击退出函数
            return true
        }
        return false
    }

    private fun exitBy2Click() {
        var tExit: Timer? = null
        if (!isExit) {
            isExit = true // 准备退出
            toast("再按一次退出应用")
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false // 取消退出
                }
            }, 1500) // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            KeySimulateUtils.simulate(KeyEvent.KEYCODE_HOME)
            System.exit(0)
        }
    }


}

